//
//  SinaOAuthViewController.swift
//  SinaWeiBo
//
//  Created by 王忠楠 on 16/9/20.
//  Copyright © 2016年 wangzn. All rights reserved.
//

import UIKit
import SVProgressHUD

//第三方登录视图控制器
//新浪开发平台提供的APPKey
let WeiboAppKey = "3937169293"

//AppSecret
let WeiboAppSecret = "56c3aa85588ec8a33b2094ef2aa51bd5"

//授权回调页
let  WeiboRedirect_Uri = "http://www.jianshu.com"


class SinaOAuthViewController: UIViewController{
    //懒加载
    private lazy var webView: UIWebView = UIWebView()
    //重写loadView
    override func loadView(){
        //解决底部webView黑条
        //改成透明解决黑条问题
        webView.isOpaque = false
        
        //设置代理
        webView.delegate = self
        
        view = webView
        
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        requestLogin()
        setupNavUI()
    }
    
    
  //请求第三方登录
    private func requestLogin() {
        //准备url地址
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Uri)"
        
        print(url)
        
        //创建urlrequest对象
        let urlRequest = URLRequest(url: URL(string: url)!)
        
        webView.loadRequest(urlRequest)
    
        
    }
    
    //设置导航栏按钮
    private func setupNavUI(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFillAction))
        title = "爱你的微博"
    }
    //点击事件处理
    @objc private func cancelAction(){
        //点击取消的时候让等待指示器删除
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }

    @objc private func autoFillAction(){
        
    print("自动填充")
        
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '17704363717';document.getElementById('passwd').value = 'nazi04191117'")

        
        
    }
    
    
}














//UIWebViewDelegate



extension SinaOAuthViewController:UIWebViewDelegate{
    
    
    //开始加载请求
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        
        
        SVProgressHUD.show()
    }
    
    
    //加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    //加载失败
    func  webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        
        SVProgressHUD.dismiss()
    }
    
    
    //将要加载请求
    func  webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //判断url是否合法
        
        guard let url = request.url else {
            
            print("url 为 nil")
            
            return false
        }
        print(url.absoluteString)
        if !url.absoluteString.hasPrefix(WeiboRedirect_Uri) {
            
            //表示不是我关心
            return true
        }
        
        //代码执行到此表示是我们关系的请求地址
        //取到地址栏的参数
        
        if let query = url.query , query.hasPrefix("code=") {
            
            //根据光标的结束位置获取子串
            
            let code = query.substring(from: "code=".endIndex)
            
            print(code)
            
            //通过code获取accesstoken
            //requestAccesstoken(code: code)
            
            
            SinaUserAccountViewModel.sharedUserAccountViewModel.requestAccesstoken(code: code, callBack: { (isSuccess) in
                if isSuccess{
                    print("登录成功")
                    self.dismiss(animated: false, completion: { 
                        //进入欢迎界面
                        NotificationCenter.default.post(name: NSNotification.Name(SwitchRootVCNotification), object: self)
                        
                        
                        
                        
                    })
                    
                }
                
            })
            
            
        }else{
            
            //取消授权
            dismiss(animated: true, completion: nil)
        }
        
        return false
    }
    
    
    
    
}














